import java.util.HashMap;
import java.util.Map;

//https://leetcode.cn/problems/minimum-number-of-frogs-croaking/
class Solution {
    public int minNumberOfFrogs(String croakOfFrogs) {
        char[] s = croakOfFrogs.toCharArray();
        int n = "croak".length();
        int[] hash = new int[n];
        // 绑定字符和其下标
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < n; i++)
            map.put("croak".charAt(i), i);
        for (char ch : s) {
            int index = map.get(ch);
            if (index == 0) {
                if (hash[n - 1] != 0)
                    hash[n - 1]--;
                hash[0]++;
            } else {
                if (hash[index - 1]-- == 0)
                    return -1;
                hash[index]++;
            }
        }
        //除最后一个字符外，哈希表中仍有其他字符存在个数
        for (int i = 0; i < n - 1; i++) {
            if (hash[i] != 0)
                return -1;
        }
        return hash[n - 1];
    }
}